# -*- coding: utf-8 -*-
import web
import json
import model
import datetime

def dumps(state, data=''):
    return json.dumps([state, data])

class sayhello:
    def GET(s, who):
        return 'hi, '+ who+'.'

class do_search :
    def GET(s, keywords):
        import search_engine
        se = search_engine.search_engine(keywords)
        return dumps(200, se.search())

class list_note:
    def GET(s, count=-1):
        ns = list(model.note.select())
        ns = [{'id':n.id, 'title':n.title} for n in ns]
        return dumps(200, ns)
    
class add_note:
    def GET(s, title):
        n = model.note(title=title)
        return dumps(200, {'id': n.id, 'title': n.title})

class remove_note:
    def GET(s, note_id):
        n = model.note.get(note_id)
        for b in n.blocks:
            b.destroySelf()
        id = n.id
        n.destroySelf()
        return dumps(200, {'id':n.id});

class rename_note:
    def GET(s, note_id, title):
        n = model.note.get(note_id)
        n.title = title
        return dumps(200, {'id': n.id, 'title': n.title})

class get_note:
    def GET(s, note_id):
        n = model.note.get(note_id)
        return dumps(200, {'id': n.id, 'title': n.title});

class list_block:
    def GET(s, note_id):
        bs = list(model.block.select(
                model.block.q.note == model.note.get(note_id),
                orderBy=model.block.q.pos
                ))
        bs = [{ 'id':b.id, 'note_id': note_id, 
                'pos':b.pos, 'content': b.content,
                'create_time': str(b.create_time),
                'modify_time':str(b.modify_time), 
                'fold': b.fold} for b in bs]
        return dumps(200, bs)

class add_block:
    def GET(s, note_id):
        now = datetime.datetime.now()
        b = model.block(
            note=model.note.get(note_id), content='<br/>', pos=0,
            create_time=now, modify_time=now, fold=0
            );
        return dumps(200,{ 'id':b.id, 'note_id': note_id, 
                'pos':b.pos, 'content': b.content,
                'create_time': str(b.create_time),
                'modify_time':str(b.modify_time), 
                'fold': b.fold} )

class remove_block:
    def GET(s, block_id):
        b = model.block.get(block_id)
        raw = { 'id':b.id, 'note_id': b.note.id, 
                'pos':b.pos, 'content': b.content,
                'create_time': str(b.create_time),
                'modify_time':str(b.modify_time), 
                'fold': b.fold}
        b.destroySelf()
        return dumps(200, raw)

class save_blocks_pos:
    def POST(s):
        i = web.input(ordered_ids='')
        ordered_ids = json.loads(i.ordered_ids)
        for i, id in enumerate(ordered_ids):
            model.block.get(id).pos = i
        return dumps(200)
        
class save_block_content:
    def POST(s, block_id):
        i = web.input(content = '')
        b = model.block.get(block_id)
        b.content = i.content.encode('utf-8')
        b.modify_time = datetime.datetime.now()
        return dumps(200)

class save_block_state:
    def GET(s, block_id, state):
        model.block.get(block_id).fold = True if int(state) == 1 else False
        return dumps(200)

class save_blocks_state:
    def POST(s):
        i = web.input(state_pairs='')
        state_pairs = json.loads(i.state_pairs)
        for pair in state_pairs:
            id, state = pair
            b = model.block.get(id)
            b.fold = int(state)
        return dumps(200)

class save_block_tags:
    def POST(s, block_id):
        i = web.input(tags = '')
        tags = i.tags
        #covert to utf-8 charset after json.loads
        tags = [ x.encode('utf-8') for x in json.loads(tags)]
        new_tagname_set = set(filter(lambda x: len(x)!=0,
                [e.strip() for e in tags]))

        b = model.block.get(block_id)
        old_tags = model.block.get(block_id).tags
        old_tagname_set = set([t.name for t in old_tags])
        attach_set = new_tagname_set.difference(old_tagname_set)
        detach_set = old_tagname_set.difference(new_tagname_set)
        
        #model.tag._connection.debug = True
        for e in attach_set:
            existed_tags = list(model.tag.selectBy(name = e))
            if len(existed_tags) == 0:
                existed_tags.append(model.tag(name=e, count=0))
            b.addTag(existed_tags[0])
            existed_tags[0].count += 1
        
        for e in detach_set:
            existed_tags = list(model.tag.selectBy(name = e))
            b.removeTag(existed_tags[0])
            existed_tags[0].count -= 1

        return dumps(200, {'block_id': b.id})

class list_tag_by_block:
    def GET(s, block_id):
        b = model.block.get(block_id)
        ts = [{ 'id':t.id, 'name': t.name,
                'count': t.count} for t in b.tags]
        
        return dumps(200, {'block_id':block_id, 'tags':ts})


